/**
 * ajax.home.jax
 * Business Logic:
 * 		Step 01: get userId from login 
 * 		Step 02: call service to get user info based on userId
 * 		Step 03: load map with user logged in
 * 		Step 04: get list of friends on facebook and call service to get position (pagination)
 * 		Step 05: update map
 * 		Step 06: back to O4 until get no friend records
 * Author: Phu
 * Date: May 26, 2014
 */
var map;
var offset = -1;
var homePosition;
var userId = '';
var markers = Array();
var infoWindows = Array();

var moveMapToFirtMaker = function() {
	map.panTo(homePosition);
}

/**
 * Load first user
 */
var loadMap = function(user) {
	//Get user login to initialize map
	markers = Array();
	infoWindows = Array();
	
	//Set profile
	setProfile(user);
	
	//set map options
	var mapOptions
	if (user.located == NULL) {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(40.111689,-78.134766),//new york
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		homePosition = new google.maps.LatLng(40.111689,-78.134766);
		map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	} else {
		homePosition = getLatLng(user.located);
		mapOptions = {
				zoom : 8,
				center : homePosition,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		homePosition = getLatLng(user.located);
		//load map with user's position
		map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
		
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		var pos = getLatLng(user.located);
		var marker = new google.maps.Marker({
		     position: homePosition,
		     map: map,
		     icon: image,
		     title: user.username,
		     draggable: true,
		     animation: google.maps.Animation.BOUNCE,
		     infoWindowIndex : offset
		});
		
		var dist = distance(homePosition.lat(), homePosition.lng(), pos.lat(), pos.lng(), 'K');
	    var label = new Label({
	        map: map,
	        title: user.fullname + ' ('+ formatRound(dist) +')'
	      });
		label.bindTo('position', marker, 'position');
		label.bindTo('text', marker, 'position');
		
		var info = getPopupInfo(user);
		var infoWindow = new google.maps.InfoWindow({
			content : info
		});
		google.maps.event.addListener(marker, "click", 
				function(e) {
					infoWindows[this.infoWindowIndex].open(map, this);
				});
		infoWindows.push(infoWindow);
		markers.push(marker);
	}
	
	
}

/**
 * Load map more 
 */
var loadMapMore = function(users) {
	
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		var user = users[i];
		if (user.located != NULL) {
			var avatar = getAvatar(user);
			var image = getIcon(avatar);
			var pos = getLatLng(user.located);
			var marker = new google.maps.Marker({
			     position: pos,
			     map: map,
			     icon: image,
			     title: user.username,
			     draggable: true,
			     infoWindowIndex : i+(offset*MAX_PAGE+1)
			 });
			
			var dist = distance(homePosition.lat(), homePosition.lng(), pos.lat(), pos.lng(), 'K');
		    var label = new Label({
		        map: map,
		        title: user.fullname + ' ('+ formatRound(dist) +')'
		      });
		    label.bindTo('position', marker, 'position');
		    label.bindTo('text', marker, 'position');
		    
		    var info = getPopupInfo(user);
		    infoWindow = new google.maps.InfoWindow({
				content : info
			});
			google.maps.event.addListener(marker, "click",function(e) {
								infoWindows[this.infoWindowIndex].open(map, this);
							});
			infoWindows.push(infoWindow);
			markers.push(marker);
		}
		
	}
	
}

/**
 * load friends of user
 */
var loadFriends = function() {
	offset = offset + 1;
	
	var url = '/me/friends?offset='+(offset*MAX_PAGE)+'&limit='+MAX_PAGE;
	
	FB.api(url, function(response) {
		if (response != null) {
			$.ajax({
				url : "/index?action=getFriends&userId="+userId,
				type: 'POST',
		        dataType: 'json',
		        data: JSON.stringify(response),
		        contentType: 'application/json; charset=utf-8',
		        mimeType: 'application/json',
				success : function(resp) {
					if (resp != null) {
						// getting the data from the response object
						var data = resp.data;
						//initialize map
						if(data.length > 0) {
							loadMapMore(data);
						} else {
							alert("No friend found!");
						}
					} else {
						alert("No record found!");
					}
				}
			});
		} else {
			alert("No record found!")
		}
	});
}

/**
 * load current user logged in phonemap
 */
var loadUser = function() {
	$.ajax({
		url : "/search?action=initMap&userId="+userId,
		type: 'GET',
        data: '',
		success : function(resp) {
			if (resp != null) {
				// getting the data from the response object
				var data = resp.data;
				//initialize map
				if(data.length > 0) {
					//load map with current user
					loadMap(data[0]);
					loadFriends();
				}
			}
		},
		error : function(resp){
			alert('Cannot get data! Please check again');
		}
	});
}

/**
 * Load map
 */
var initMap = function() {
	offset = -1;
	userId = $.cookie('useraccount');
	if (userId != '' && userId != null) {
		//load current user with map
		loadUser();
	} else {
		//Go to index page
		document.location.href = '/index.html';
	}
}




